package com.zkflzl.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkflzl.store.common.BaseResponse;
import com.zkflzl.store.common.ErrorCode;
import com.zkflzl.store.common.ResultUtils;
import com.zkflzl.store.exception.ThrowUtils;
import com.zkflzl.store.mapper.StockMapper;
import com.zkflzl.store.model.dto.msg.MsgAddRequest;
import com.zkflzl.store.model.dto.shopstock.ShopStockAddRequest;
import com.zkflzl.store.model.dto.stock.StockAddRequest;
import com.zkflzl.store.model.dto.stock.StockListRequest;
import com.zkflzl.store.model.dto.stock.StockOutRequest;
import com.zkflzl.store.model.entity.Stock;
import com.zkflzl.store.model.entity.User;
import com.zkflzl.store.service.MsgService;
import com.zkflzl.store.service.ShopStockService;
import com.zkflzl.store.service.StockService;
import com.zkflzl.store.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 21582
 * @description 针对表【tb_stock(库存表)】的数据库操作Service实现
 * @createDate 2024-03-20 09:40:30
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock>
        implements StockService {

    @Resource
    private UserService userService;
    @Resource
    private ShopStockService shopStockService;

    @Resource
    private MsgService msgService;


    @Override
    public BaseResponse inStock(StockAddRequest stockAddRequest, HttpServletRequest request) {
        User user = userService.getLoginUser(request);

        // 权限校验
        boolean admin = userService.isAdmin(request);
        if (!admin) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR);
        }

        // 参数校验
        String name = stockAddRequest.getName();
        String location = stockAddRequest.getLocation();
        String price = stockAddRequest.getPrice();
        Integer quantity = stockAddRequest.getQuantity();
        Long userId = user.getId();
        if (StringUtils.isAnyBlank(name, location, price, quantity.toString())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        Stock stock = new Stock();
        stock.setUserId(userId);
        BeanUtils.copyProperties(stockAddRequest, stock);

        boolean save = this.save(stock);

        if (!save) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success("添加成功");
    }

    @Override
    @Transactional
    public BaseResponse outStock(StockOutRequest stockOutRequest, HttpServletRequest request) {
        // 权限校验
        boolean admin = userService.isAdmin(request);
        if (!admin) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR);
        }

        String stockId = stockOutRequest.getStockId();
        String shopId = stockOutRequest.getShopId();
        String storeId = stockOutRequest.getStoreId();
        Integer quantity = stockOutRequest.getOutQuantity();
        if (StringUtils.isAnyBlank(stockId, shopId, quantity.toString())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        // 库存量是否满足扣减
        Stock stock = this.getById(stockId);
        ThrowUtils.throwIf(stock == null, ErrorCode.NOT_FOUND_ERROR, "库存商品不存在");
        ThrowUtils.throwIf(stock.getQuantity() - (stock.getOutQuantity() + quantity) < 0,
                ErrorCode.OPERATION_ERROR, "库存不足");

        // 指定门店获取库存
        ShopStockAddRequest shopStockAddRequest = new ShopStockAddRequest();
        shopStockAddRequest.setStoreId(Long.valueOf(storeId));
        shopStockAddRequest.setQuantity(quantity);
        shopStockAddRequest.setShopId(Long.valueOf(shopId));

        // 门店商品添加库存
        shopStockService.updateShopStock(shopStockAddRequest, request);


        // 更新出库数量
        stock.setOutQuantity(stock.getOutQuantity() + quantity);

        boolean update = this.updateById(stock);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);

        // 发消息给管理员
        MsgAddRequest msgAddRequest = new MsgAddRequest();
        msgAddRequest.setContent("出库id为：" + stockId +
                "---收货门店id为：" + shopId +
                "--商品id为：" + storeId +
                "---出库数量为：" + quantity);

        msgService.addMsg(msgAddRequest, request);

        return ResultUtils.success("出库成功");
    }

    @Override
    public BaseResponse delStock(String stockId, HttpServletRequest request) {
        boolean admin = userService.isAdmin(request);
        ThrowUtils.throwIf(!admin, ErrorCode.NO_AUTH_ERROR);

        if (StringUtils.isBlank(stockId)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        boolean remove = this.removeById(stockId);
        ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success("删除成功");
    }

    @Override
    public BaseResponse selStock(StockListRequest stockListRequest, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限访问");
        }
        String stockId = stockListRequest.getStockId();
        long current = stockListRequest.getCurrent();
        long pageSize = stockListRequest.getPageSize();
        String sortField = stockListRequest.getSortField();
        String sortOrder = stockListRequest.getSortOrder();

        // 走指定查询
        if (!StringUtils.isBlank(stockId)) {
            Stock stock = this.getById(stockId);
            return ResultUtils.success(stock);
        }

        Page<Stock> page = new Page<>(current, pageSize);
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isBlank(sortField) && !StringUtils.isBlank(sortOrder)) {
            queryWrapper.orderBy(true, "asc".equals(sortOrder), sortField);
        }

        Page<Stock> stockPage = this.page(page, queryWrapper);
        return ResultUtils.success(stockPage);
    }

    @Override
    public BaseResponse updateStock(Long id, Long quantity, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限访问");
        }

        UpdateWrapper<Stock> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("id", id)
                .setSql("quantity = quantity + " + quantity);
        boolean update = this.update(updateWrapper);

        ThrowUtils.throwIf(!update, ErrorCode.SYSTEM_ERROR, "库存更新失败");
        return ResultUtils.success("库存更新成功");
    }
}




